<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/17
 */

namespace app\classroom\controller;

use app\classroom\model\ClassroomModel;
use app\classroom\service\ClassroomService;
use app\portal\service\PostService;
use app\system\model\SchoolModel;
use cmf\controller\AdminBaseController;
use think\Db;

class ClassroomController extends AdminBaseController
{
    /*
     * 教室列表
     */
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $where = [];
        //店铺ID
        $where['c.shop_id'] = ['=', $this->admin_shop_id];

        if (!empty($param['name'])) {
            //教室名称
            $where['c.name'] = ['like', '%' . trim($param['name']) . '%'];
        }
        if (!empty($param['school_id'])) {
            //校区
            $where['c.school_id'] = ['=', intval($param['school_id'])];
        }

        if (isset($param['start_nums']) && isset($param['end_nums']) && is_numeric($param['start_nums']) && is_numeric($param['end_nums'])) {
            //容纳人数
            $where['c.student_nums'] = [['>=', $param['start_nums']], ['<=', $param['end_nums']]];
        } else {
            if (isset($param['start_nums']) && is_numeric($param['start_nums'])) {
                $where['c.student_nums'] = ['>=', $param['start_nums']];
            }
            if (isset($param['end_nums']) && is_numeric($param['end_nums'])) {
                $where['c.student_nums'] = ['<=', $param['end_nums']];
            }
        }

        if (isset($param['start']) && isset($param['end']) && is_numeric($param['start']) && is_numeric($param['end'])) {
            //班级数量
            $where['c.class_nums'] = [['>=', $param['start']], ['<=', $param['end']]];
        } else {
            if (isset($param['start']) && is_numeric($param['start'])) {
                $where['c.class_nums'] = ['>=', $param['start']];
            }
            if (isset($param['end']) && is_numeric($param['end'])) {
                $where['c.class_nums'] = ['<=', $param['end']];
            }
        }

        //分页url额外参数
        $page_query = [
            'name' => isset($param['name']) ? $param['name'] : '',
            'school_id' => isset($param['school_id']) ? $param['school_id'] : '',
            'start_nums' => isset($param['start_nums']) ? $param['start_nums'] : '',
            'end_nums' => isset($param['end_nums']) ? $param['end_nums'] : '',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        //排序
        $sort = ['c.update_time' => 'desc', 'c.list_order' => 'desc'];

        $room_model = new ClassroomModel();
        $data = $room_model->getClassroom($where, $sort, $limit, $page_query);

        //获取校区
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('schools', $schools);
        $this->assign('param', $param);
        $this->assign('classroom', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /*
     * 添加教室
     */
    public function add()
    {
        //校区
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('campus', $schools);
        return $this->fetch();
    }

    //教室模板生成
    public function addPost()
    {
        $cur_time = time();
        $validate = validate('Classroom');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if(empty(trim($data['name']))){
                $this->error('教室名称不能为空');
            }

            $model = new ClassroomModel();
            $total = $model->where('shop_id', '=', $this->admin_shop_id)
                ->where('delete_time', '=', 0)
                ->where(['school_id' => $data['school_id']])
                ->where(['name' => trim($data['name'])])
                ->count();
            if (isset($total) && $total >= 1) {
                $this->error('该教室已存在');
            }
            if (empty($data['vip']) && empty($data['aisle'])) {
                $data['student_nums'] = $data['rows'] * $data['cols'];
            }
            if (!empty($data['vip'])) {
                //预留座位
                $data['vip'] = serialize($data['vip']);
            }
            if (!empty($data['aisle'])) {
                //过道
                $data['aisle'] = serialize($data['aisle']);
            }

            $data['create_time'] = $cur_time;

            $id = $model->insertGetId($data);
            $pk = $id; //主键
            $table = 'classroom';//数据表名
            if ($id) {
                //记录日志
                $content = lang('ADD_CLASSROOM', ['name' => $data['name']]);
                do_log($content, $pk, $table, $cur_time);

                $this->success('添加成功', 'classroom/index', '', 2);
            } else {
                $this->error("添加失败");
            }
        }
    }


    /*
     * 编辑教室
     */
    public function edit($id)
    {
        if (empty($id)) {
            $this->error('参数为空', 'classroom/index');
        }
        $model = new ClassroomModel();
        $data = $model->where('id', $id)->find();
        if (empty($data->id)) {
            $this->error('没有该教室信息', 'classroom/index');
        }
        if (!empty($data->vip)) {
            $data->vip = unserialize($data->vip);
        }
        if (!empty($data->aisle)) {
            $data->aisle = unserialize($data->aisle);
        }

        //获取校区
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('campus', $schools);
        $this->assign('data', $data);
        return $this->fetch();

    }

    /*
     * 保存编辑教室
     */
    public function editPost()
    {
        $cur_time = time();
        $validate = validate('Classroom');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $id = $data['id'];
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if(empty(trim($data['name']))){
                $this->error('教室名称不能为空');
            }

            $model = new ClassroomModel();
            $filter_id = [
                'id' => ['eq', intval($id)],
                'shop_id' => ['eq', $this->admin_shop_id]
            ];
            $result = $model->getClassroomByField($filter_id);
            if (isset($result->id) && empty($result->id)) {
                $this->error('没有该教室', 'classroom/index');
            }

            $filter = [
                'school_id' => ['eq', $data['school_id']],
                'name' => ['eq', trim($data['name'])],
                'shop_id' => ['eq', $this->admin_shop_id]
            ];
            $res = $model->getClassroomByField($filter);
            if (isset($res->id) && ($res->id != $id)) {
                $this->error('该教室已存在');
            }
            if (empty($data['vip']) && empty($data['aisle'])) {
                $data['student_nums'] = $data['rows'] * $data['cols'];
            }

            if (!empty($data['vip'])) {
                //预留座位
                $data['vip'] = serialize($data['vip']);
            }
            if (!empty($data['aisle'])) {
                //过道
                $data['aisle'] = serialize($data['aisle']);
            }

            $data['create_time'] = $cur_time;
            $data['update_time'] = $cur_time;

            $res = $model->editClassroom($data);
            $pk = $id; //主键
            $table = 'classroom';//数据表名
            if ($res) {
                //记录日志
                $content = lang('EDIT_CLASSROOM', ['name' => $data['name']]);
                do_log($content, $pk, $table, $cur_time);

                $this->success('编辑成功', 'classroom/index', '', 2);
            } else {
                $this->error("编辑失败");
            }
        }
    }

    /*
     * 删除
     */
    public function delete()
    {
        $cur_time = time();
        $table = 'classroom';
        $room_model = new ClassroomModel();

        $param = $this->request->param();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            //记录日志
            $pk = $id;
            $name = Db::name('classroom')->where('id', $id)->value('name');
            $content = lang('DELETE_CLASSROOM', ['name' => $name]);

        } else {
            $id = $this->request->param('ids/a');
            //记录日志
            $pk = implode(',', $id);
            $content = lang('BATCH_DELETE', ['name' => '教室']);
        }

        $result = $room_model->deleteClassroom($id, $cur_time);
        if ($result) {
            //记录日志
            do_log($content, $pk, $table, $cur_time);

            $this->success("删除成功！", '');
        } else {
            $this->error('删除失败！');
        }
    }


}